package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-mnger/cache"
	"novel-mnger/models"
	"novel-mnger/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	//判断密码是否错误三次
	redis_Key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_Key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次。禁止登录",
		})
		return
	}

	//判断用户是否存在
	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	//判断密码是否正确
	if user.Password != pkg.Md5str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_Key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_Key, 3, time.Hour*2)

			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return

	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": user,
	})
	return

}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var users []models.User

	redis_Key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_Key).Result()
	if cacheData == "" {
		models.DB.
			Offset(offset).
			Limit(size).
			Debug().
			Find(&users)
		jsonData, _ := json.Marshal(users)
		cache.Rdb.Set(cache.Ctx, redis_Key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &users)
	}

	var total int64
	models.DB.Model(&models.User{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  users,
		"total": total,
	})
	return

}

func Detail(c *gin.Context) {
	id := c.Query("id")

	var user models.User

	redis_Key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_Key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).First(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_Key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &user)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": user,
	})
	return

}
